package org.kepler.chat.api.infra.util;

import org.springframework.security.web.savedrequest.SavedRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * 
 * @author ake
 *
 * Aug 3, 2016
 */
public class WebUtil {
    private static final String XML_HTTP_REQUEST = "XMLHttpRequest";
    private static final String X_REQUESTED_WITH = "X-Requested-With";

    private static final String CONTENT_TYPE = "Content-type";
    private static final String CONTENT_TYPE_JSON = "application/json";

    public static boolean isAjax(HttpServletRequest request) {
        return XML_HTTP_REQUEST.equals(request.getHeader(X_REQUESTED_WITH));
    }

    public static boolean isAjax(SavedRequest request) {
        return request.getHeaderValues(X_REQUESTED_WITH).contains(XML_HTTP_REQUEST);
    }

    public static boolean isContentTypeJson(SavedRequest request) {
        return request.getHeaderValues(CONTENT_TYPE).contains(CONTENT_TYPE_JSON);
    }

    /**
     * 获取所有的请求参数
     * @param request
     * @return
     */
    public static Map<Object,Object> getParameterMap(HttpServletRequest request){
        Map<Object,Object> parameterMap = new HashMap<Object,Object>() ;
        @SuppressWarnings("rawtypes")
        Enumeration parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            Object parameterName = parameterNames.nextElement() ;
            String[] parameterValues = request.getParameterValues(parameterName.toString());
            if (parameterValues.length == 1) {
                String paramValue = parameterValues[0];
                if (paramValue.length() != 0) {
                    parameterMap.put(parameterName, paramValue);
                }
            }
        }
        return parameterMap ;
    }

}
